package cn.unknownerror.ueteam.gui.frames;

import cn.unknownerror.ueteam.data.ConfigurationManager;
import cn.unknownerror.ueteam.gui.DynamicButton;
import cn.unknownerror.ueteam.team.ITeam;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.ArrayList;
import java.util.List;

public class CommandButton extends DynamicButton<ITeam> {

    protected ConfigurationManager config;
    protected String name;

    public CommandButton(ConfigurationManager config,String name){
        super(null);
        this.config=config;
        this.name=name;
    }

    @Override
    public ItemStack onCreate(ITeam team) {
        return createItemByConfig(name,team);
    }

    @Override
    public void onClick(Player player) {
        Bukkit.dispatchCommand(player,config.getString("GUI.Customize."+name+".func"));
    }

    private ItemStack createItemByConfig(String node, ITeam team){
        String str="GUI.Customize."+node+".";
        ItemStack item=new ItemStack(Material.getMaterial(str+"material"));
        ItemMeta meta=item.getItemMeta();
        meta.setDisplayName(replace(config.getString(str+"display_name"),team));
        List<String> lore=new ArrayList<>();
        for(String str1:config.getStringList(str+"lore")){
            lore.add(replace(str1,team));
        }
        meta.setLore(lore);
        item.setItemMeta(meta);
        return item;
    }

    private String replace(String str,ITeam team){
        return str.replaceAll("%team_name%",team.getName())
                .replaceAll("%member_sum%",String.valueOf(team.getMembers().size())
                        .replaceAll("%max_member%",String.valueOf(team.getMaxmember()))
                        .replaceAll("%team_captain%", Bukkit.getOfflinePlayer(team.getCaptain()).getName())
                        .replaceAll("%team_state%",team.getTeamState()+""));
    }

}
